package cn.net.xyan.pay.wechat.service

import cn.net.xyan.kotlin.logger
import cn.net.xyan.pay.core.service.Button
import cn.net.xyan.pay.core.service.ButtonType
import cn.net.xyan.pay.core.service.MenuService
import me.chanjar.weixin.common.bean.menu.WxMenu
import me.chanjar.weixin.common.bean.menu.WxMenuButton
import me.chanjar.weixin.mp.api.WxMpService
import org.springframework.beans.factory.annotation.Autowired

/**
 * Created by zarra on 2017/4/12.
 */

class WeChatMenuService : MenuService {

    lateinit var wxMpService: WxMpService

    val weChatRootURL = "http://wcloud.xyan.net.cn/mp/weChat/redirect"

    fun Button.build(): WxMenuButton {
        val button = WxMenuButton()
        button.name = name
        when (type) {
            ButtonType.CLICK -> {
                button.type = "click";button.key = content
            }
            ButtonType.URL -> {
                button.type = "view"
                button.url = "$weChatRootURL/$content"
                logger.info("button url ${button.url}")
            }
        }

        button.subButtons = children.map {
            it.build()
        }

        return button
    }


    override fun deleteAll() {
        wxMpService.menuService.menuDelete()

        logger.info("delete all ok")
    }

    override fun addAll(buttons: List<Button>) {
        wxMpService.menuService.menuDelete()

        val menu = WxMenu()

        menu.buttons = buttons.map { it.build() }

        val result = wxMpService.menuService.menuCreate(menu)

        logger.info("addAll result:$result")

    }

}